package com.zzl.alligator.framework.config;

import com.zzl.alligator.framework.security.filter.JwtAuthenticationTokenFilter;
import com.zzl.alligator.framework.security.filter.VerifyCodeFilter;
import com.zzl.alligator.framework.security.hanlder.AuthenticationAccessDeniedHandler;
import com.zzl.alligator.framework.security.hanlder.AuthenticationEntryPointImpl;
import com.zzl.alligator.framework.security.hanlder.LoginFailureHandler;
import com.zzl.alligator.framework.security.hanlder.LoginSuccessHandler;
import com.zzl.alligator.framework.security.hanlder.LogoutSuccessHandlerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring security 配置类
 *
 * @author zhouziliang
 * @since 2020/6/24 11:06 上午
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private VerifyCodeFilter verifyCodeFilter;

    @Autowired
    private AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;

    /**
     * 配置节点
     *
     * @param http
     * @throws Exception anyRequest          |   匹配所有请求路径
     *                   access              |   SpringEl表达式结果为true时可以访问
     *                   anonymous           |   匿名可以访问
     *                   denyAll             |   用户不能访问
     *                   fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     *                   hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     *                   hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     *                   hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     *                   hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     *                   hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     *                   permitAll           |   用户可以任意访问
     *                   rememberMe          |   允许通过remember-me登录的用户访问
     *                   authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 由于不使用session 所以禁用csrf
                .csrf().disable()
                // session 生成策略
                /*
                    ALWAYS - 总是创建HttpSession
                    IF_REQUIRED - Spring Security只会在需要时创建一个HttpSession
                    NEVER - Spring Security不会创建HttpSession，但如果它已经存在，将可以使用HttpSession
                    STATELESS - Spring Security永远不会创建HttpSession，它不会使用HttpSession来获取SecurityContext
                 */
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

                .formLogin()
                .loginProcessingUrl("/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
                .permitAll().and()

                // 过滤请求
                .authorizeRequests()
                // 对于登录login 验证码captchaImage 允许匿名访问
                .antMatchers("/login", "/captchaImage").anonymous()
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .antMatchers("/profile/**").anonymous()
                .antMatchers("/common/download**").anonymous()
                .antMatchers("/common/download/resource**").anonymous()
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                // 认证失败处理
                .exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPoint).and()
                .logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler).and()
                // 允许iframe嵌入
                .headers().frameOptions().disable();

        //验证码过滤器
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加JWT filter
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
